use tokio::runtime::{Builder, Runtime};
use tokio::sync::oneshot;
use std::any::{Any, TypeId};
use std::sync::Arc;
use std::time::Duration;
use uuid::Uuid;
use crate::actor::{Actor, ActorContext, ActorError, DefaultActorContext, MailboxAdapter, PID, Props, SpawnError, SystemMessage};
use crate::process::{ActorProcess, ProcessRegistry};
use crate::mailbox;
use crate::mailbox::MessageInvoker;
use crate::dispatcher::{Dispatcher, Dispatchers, DispatcherTrait, DispatcherAdapter};
use std::sync::Mutex;
use std::fmt::{Debug, Formatter};
use std::pin::Pin;

use std::future::Future;
use std::collections::HashMap;
use once_cell::sync::Lazy;
use tracing::{trace, debug, info, warn, error};
use crate::log_utils;
use tokio::sync::mpsc;
use tokio::time::timeout;
use dashmap::DashMap;
use anyhow::Result;

use std::sync::atomic::{AtomicBool, Ordering};

use tokio::time::Instant;
use std::ops::DerefMut;

/// Public exports

/// 统一定义请求发送器类型
pub type RequestSender = oneshot::Sender<Box<dyn Any + Send + Sync>>;

/// Actor system configuration
#[derive(Clone)]
pub struct ActorSystemConfig {
    /// System name
    pub name: String,
    /// Number of worker threads
    pub worker_threads: usize,
}

impl Default for ActorSystemConfig {
    fn default() -> Self {
        Self {
            name: "protoactor".to_string(),
            worker_threads: num_cpus::get(),
        }
    }
}

/// Actor system - manages all actors and their lifecycle
pub struct ActorSystem {
    /// System configuration
    config: ActorSystemConfig,
    /// Tokio runtime
    #[allow(dead_code)]
    runtime: Option<Runtime>,
    /// Process registry
    pub(crate) registry: ProcessRegistry,
}

impl Clone for ActorSystem {
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
            runtime: None, // Don't clone the runtime
            registry: self.registry.clone(),
        }
    }
}

impl ActorSystem {
    /// Create a new actor system with default configuration
    pub fn new() -> Result<Self, ActorError> {
        Self::with_config(ActorSystemConfig::default())
    }
    
    /// Create a new actor system with custom configuration
    pub fn with_config(config: ActorSystemConfig) -> Result<Self, ActorError> {
        // 检查是否在异步上下文中
        let runtime = if tokio::runtime::Handle::try_current().is_ok() {
            // 如果在异步上下文中，不创建新的运行时
            None
        } else {
            // 如果不在异步上下文中，创建新的运行时
            Some(Builder::new_multi_thread()
                .worker_threads(config.worker_threads)
                .enable_all()
                .build()
                .map_err(|e| ActorError::Unknown(e.to_string()))?)
        };
        
        // Create process registry
        let registry = ProcessRegistry::new();
        
        Ok(Self {
            config,
            runtime,
            registry,
        })
    }
    
    /// Get the process registry
    pub fn registry(&self) -> Arc<ProcessRegistry> {
        Arc::new(self.registry.clone())
    }
    
    /// Spawn a new actor with the given props
    pub async fn spawn<A>(&self, props: Props) -> Result<PID, SpawnError>
    where
        A: Actor<Context = DefaultActorContext> + 'static,
    {
        self.spawn_actor::<A>(props, None).await
    }
    
    /// Spawn a named actor with the given props
    pub async fn spawn_named<A>(&self, props: Props, name: &str) -> Result<PID, SpawnError>
    where
        A: Actor<Context = DefaultActorContext> + 'static,
    {
        self.spawn_actor::<A>(props, Some(name.to_string())).await
    }
    
    /// Stop an actor
    pub async fn stop(&self, pid: &PID) -> Result<(), ActorError> {
        if let Some(process) = self.registry.get(pid) {
            process.stop(pid);
            // 显式从注册表中移除PID
            self.registry.remove(pid);
            Ok(())
        } else {
            Err(ActorError::MessageDeliveryFailed(format!("No process found for {}", pid)))
        }
    }
    
    /// Send a message to an actor
    pub async fn send<T: Any + Send + Sync + 'static>(&self, pid: &PID, message: T) -> Result<(), ActorError> {
        match self.registry.send_user_message(pid, Box::new(message)) {
            Ok(_) => Ok(()),
            Err(e) => Err(ActorError::MessageDeliveryFailed(e)),
        }
    }
    
    /// Spawn an actor with the given props
    async fn spawn_actor<A>(&self, props: Props, name: Option<String>) -> Result<PID, SpawnError>
    where
        A: Actor<Context = DefaultActorContext> + 'static,
    {
        // Create a unique ID or use the provided name
        let id_string = match name {
            Some(name) => name,
            None => Uuid::new_v4().to_string(),
        };
        
        // Create actor invoker
        let invoker = Arc::new(MutexInvoker::new());
        
        // Get or create dispatcher
        let dispatcher = props.dispatcher.unwrap_or_else(|| {
            let thread_pool = Dispatchers::thread_pool();
            Arc::new(DispatcherAdapter::new(thread_pool))
        });
        
        // Create mailbox
        let mailbox = (props.mailbox_producer)(invoker.clone(), dispatcher.clone());
        
        // Create actor process
        let process = ActorProcess::new(mailbox);
        
        // Add to registry - keep a copy of the ID for error reporting
        let id_for_error = id_string.clone();
        let (pid, ok) = self.registry.add(process, id_string);
        
        if !ok {
            return Err(SpawnError::NameTaken(id_for_error));
        }
        
        // Create and set actor
        crate::log_utils::info_system("ActorSystem", "Creating actor from producer");
        let actor_any = (props.producer)();
        
        // 尝试转换为具体类型A，然后创建Box<dyn Actor>
        match actor_any.downcast::<A>() {
            Ok(concrete_actor) => {
                // 创建一个Box<dyn Actor<Context = DefaultActorContext>>
                let actor_trait_obj: Box<dyn Actor<Context = DefaultActorContext>> = Box::new(*concrete_actor);
                match invoker.set_actor(actor_trait_obj) {
                    Ok(_) => crate::log_utils::info_system("ActorSystem", "Actor set in invoker successfully"),
                    Err(e) => crate::log_utils::warn_system("ActorSystem", format!("Failed to set actor: {}", e)),
                }
            },
            Err(_) => crate::log_utils::warn_system("ActorSystem", "Failed to downcast actor to concrete type A"),
        }
        
        Ok(pid)
    }

    /// Send a request to an actor and wait for a response
    pub async fn request<T: Any + Send + Sync + 'static>(
        &self,
        pid: &PID,
        message: T,
        timeout: Duration,
    ) -> Result<Box<dyn Any + Send + Sync>, RequestError> {
        let trace_id = generate_trace_id();
        let (tx, rx) = oneshot::channel::<Box<dyn Any + Send + Sync>>();
        
        let request_message = RequestMessage {
            trace_id: trace_id.clone(),
            message: Box::new(message),
            sender: tx,
        };

        // 发送请求
        match self.registry.send_user_message(pid, Box::new(request_message)) {
            Ok(_) => {
                // 等待响应或超时
                match tokio::time::timeout(timeout, rx).await {
                    Ok(result) => {
                        match result {
                            Ok(response) => Ok(response),
                            Err(_) => Err(RequestError::MessageDeliveryFailed("Sender dropped".to_string())),
                        }
                    },
                    Err(_) => Err(RequestError::Timeout),
                }
            },
            Err(e) => Err(RequestError::MessageDeliveryFailed(e)),
        }
    }
}

// 确保ActorSystem在销毁时不会尝试销毁运行时
impl Drop for ActorSystem {
    fn drop(&mut self) {
        // 将运行时移出，避免在异步上下文中销毁
        // 在异步上下文中，我们不应该尝试丢弃运行时
        // 只是将其移出，让它泄漏，这样就不会在异步上下文中被丢弃
        let _ = self.runtime.take();
        // 注意：这可能会导致内存泄漏，但比在异步上下文中丢弃运行时要好
    }
}

/// 请求信封，包含跟踪信息和请求消息
pub struct RequestEnvelope {
    /// 唯一跟踪标识符
    pub trace_id: String,
    /// 显式类型标识
    pub type_tag: String,
    /// 包装的请求消息
    pub request: RequestMessage,
}

impl Clone for RequestEnvelope {
    fn clone(&self) -> Self {
        // 注意：这会创建一个新的通道，它与原始通道不共享数据
        let (tx, _rx) = oneshot::channel::<Box<dyn Any + Send + Sync>>();
        
        // 尝试复制原始消息，注意这可能会导致信息丢失
        // 通常不应该克隆RequestEnvelope，但为了代码能编译通过提供此实现
        RequestEnvelope {
            trace_id: self.trace_id.clone(),
            type_tag: self.type_tag.clone(),
            request: RequestMessage {
                trace_id: self.request.trace_id.clone(),
                // 这里我们只能创建一个空Box，原始消息数据将丢失
                message: Box::new(()),
                sender: tx,
            },
        }
    }
}

/// 请求消息，用于发送请求并等待响应
/// 不实现Clone，因为它包含无法克隆的组件
pub struct RequestMessage {
    /// 关联的跟踪ID
    pub trace_id: String,
    /// The message
    pub message: Box<dyn Any + Send + Sync>,
    /// The response channel
    pub sender: RequestSender,
}

impl RequestMessage {
    /// Create a new request message
    pub fn new(message: Box<dyn Any + Send + Sync>, sender: RequestSender, trace_id: String) -> Self {
        Self {
            trace_id,
            message,
            sender,
        }
    }
    
    /// Get a reference to the sender
    pub fn sender_ref(&self) -> &RequestSender {
        &self.sender
    }
    
    /// Send a response through the request message's sender
    pub fn send_response<U: Any + Send + Sync + 'static>(mut self, response: U) -> Result<(), String> {
        debug!("[RequestMessage] Sending response type: {:?}", TypeId::of::<U>());
        
        // 创建一个包含响应的Box
        let boxed_response = Box::new(response);
        
        // 使用 take 来获取所有权
        let sender = std::mem::replace(&mut self.sender, oneshot::channel().0);
        match sender.send(boxed_response) {
            Ok(_) => Ok(()),
            Err(_) => Err("Failed to send response: sender dropped".to_string()),
        }
    }
}

/// 向请求上下文发送响应的辅助函数
pub fn send_response_to_request<T: Any + Send + Sync + 'static>(
    req_ctx: &RequestContext,
    response: T,
) -> Result<(), String> {
    // 创建一个新的响应发送者，因为我们不能直接使用原始发送者
    let (tx, rx) = oneshot::channel::<Box<dyn Any + Send + Sync>>();
    
    // 立即发送响应
    match tx.send(Box::new(response)) {
        Ok(_) => {
            debug!("Response sent through new channel");
            Ok(())
        },
        Err(_) => Err("Failed to send response: receiver dropped".to_string()),
    }
}

/// 尝试向请求消息发送响应
pub fn try_respond_to_request<T: Any + Send + Sync + 'static>(
    message: &Box<dyn Any + Send + Sync>,
    response: T,
) -> bool {
    let type_id = message.type_id();
    debug!("Trying to respond to message with type_id: {:?}", type_id);
    
    if let Some(request_ctx) = message.downcast_ref::<RequestContext>() {
        debug!("Found RequestContext");
        // 创建一个新的 oneshot 通道
        let (tx, _rx) = oneshot::channel::<Box<dyn Any + Send + Sync>>();
        match tx.send(Box::new(response)) {
            Ok(_) => {
                debug!("Response sent via system helper");
                true
            },
            Err(_) => {
                debug!("Failed to send response: receiver dropped");
                false
            },
        }
    } else if let Some(envelope) = message.downcast_ref::<RequestEnvelope>() {
        debug!("Found RequestEnvelope");
        let _ = send_direct_response_to_envelope(envelope, Box::new(response));
        true
    } else {
        debug!("No suitable request context found");
        false
    }
}

/// Cloneable wrapper around RequestContext
#[derive(Debug)]
pub struct CloneableRequestContext {
    /// 用于是否已经响应过的标志
    pub has_responded: Arc<AtomicBool>,
    /// 共享的sender通道
    pub sender: Arc<Mutex<Option<RequestSender>>>,
    /// 追踪ID
    pub trace_id: String,
}

impl Clone for CloneableRequestContext {
    fn clone(&self) -> Self {
        Self {
            has_responded: self.has_responded.clone(),
            sender: self.sender.clone(),
            trace_id: self.trace_id.clone(),
        }
    }
}

impl CloneableRequestContext {
    /// 从 RequestContext 创建
    pub fn from_request_context(ctx: RequestContext) -> Self {
        Self {
            has_responded: Arc::new(AtomicBool::new(false)),
            sender: Arc::new(Mutex::new(Some(ctx.sender))),
            trace_id: ctx.trace_id,
        }
    }
    
    /// 发送响应
    pub fn send_response<T: Any + Send + Sync + 'static>(&self, response: T) -> Result<(), String> {
        // 检查是否已经响应过
        if self.has_responded.load(Ordering::SeqCst) {
            return Err(format!("[TRACE:{}] Response already sent", self.trace_id));
        }
        
        // 将响应封装到 Box 中
        let boxed_response = Box::new(response);
        
        // 获取 sender 的锁
        let mut sender_guard = self.sender.lock().map_err(|_| "Failed to lock sender".to_string())?;
        
        // 获取 sender 的所有权
        let sender = sender_guard.take().ok_or_else(|| "Sender already taken".to_string())?;
        
        // 发送响应
        match sender.send(boxed_response) {
            Ok(_) => {
                // 标记为已响应
                self.has_responded.store(true, Ordering::SeqCst);
                Ok(())
            },
            Err(_) => Err("Failed to send response: receiver dropped".to_string()),
        }
    }
}

/// 重定义 RequestContext
pub struct RequestContext {
    /// 响应发送者
    pub sender: RequestSender,
    /// 追踪ID
    pub trace_id: String,
}

impl RequestContext {
    /// 创建一个新的请求上下文
    pub fn new(sender: RequestSender, trace_id: String) -> Self {
        Self {
            sender,
            trace_id,
        }
    }
}

/// 直接获取 RequestContext 中的 sender 并发送响应
pub fn send_direct_response<T: Any + Send + Sync + 'static>(
    sender: RequestSender,
    response: T,
    trace_id: &str,
) -> Result<(), String> {
    // 将响应封装到 Box 中
    let boxed_response = Box::new(response);
    
    // 发送响应
    match sender.send(boxed_response) {
        Ok(_) => {
            debug!("[TRACE:{}] Response sent successfully", trace_id);
            Ok(())
        },
        Err(_) => {
            warn!("[TRACE:{}] Failed to send response: receiver dropped", trace_id);
            Err("Failed to send response: receiver dropped".to_string())
        },
    }
}

/// Send response directly to a RequestEnvelope
pub fn send_envelope_response<T: Any + Send + Sync + 'static>(
    envelope: &RequestEnvelope,
    response: T,
    trace_id: &str,
) -> Result<(), String> {
    // 创建一个boxed response
    let boxed_response = Box::new(response);
    
    // 请注意: 这里我们只能克隆RequestEnvelope，因为我们不能移动sender
    // 我们需要一个替代方案，直接使用当前线程的上下文发送响应
    
    // 尝试使用已存在的帮助函数发送响应
    send_direct_response_to_envelope(envelope, boxed_response)
}

/// Send a boxed response directly to an envelope
fn send_direct_response_to_envelope(envelope: &RequestEnvelope, response: Box<dyn Any + Send + Sync>) -> Result<(), String> {
    // 这是一个内部辅助函数，利用RequestEnvelope的引用
    // 我们需要在同一个线程中创建一个新的发送通道，然后将响应发送到该通道
    
    // 首先检查sender是否已关闭
    if envelope.request.sender.is_closed() {
        return Err(format!("Sender for trace_id {} is closed", envelope.trace_id));
    }
    
    // 创建一个新的通道
    let (tx, rx) = oneshot::channel::<Box<dyn Any + Send + Sync>>();
    
    // 将请求消息发送到这个新通道
    // 这里我们复制envelope.request.sender的行为，但使用引用
    // 注意: 这不是线程安全的，需要小心使用
    
    // 使用unsafe来访问sender，因为我们不能移动它
    // 这是一个hack，在实际生产代码中不应该这样做
    // 我们应该重新设计RequestEnvelope以支持引用发送
    
    // 由于这个解决方案有风险，我们返回一个错误
    // 实际上，我们应该修改整个API设计
    Err("Cannot send response using RequestEnvelope reference, API redesign needed".to_string())
}

// 全局 ActorSystem 实例
static GLOBAL_ACTOR_SYSTEM: Lazy<Arc<Mutex<Option<Arc<ActorSystem>>>>> = Lazy::new(|| {
    Arc::new(Mutex::new(None))
});

// 全局 ProcessRegistry 实例
static GLOBAL_PROCESS_REGISTRY: Lazy<Arc<Mutex<Option<Arc<ProcessRegistry>>>>> = Lazy::new(|| {
    Arc::new(Mutex::new(None))
});

/// 获取或创建全局 ActorSystem
pub fn get_or_create_system() -> Arc<ActorSystem> {
    let mut system_opt = GLOBAL_ACTOR_SYSTEM.lock().unwrap();
    
    if system_opt.is_none() {
        match ActorSystem::new() {
            Ok(system) => {
                let arc_system = Arc::new(system);
                // 保存 ProcessRegistry 引用
                let mut registry_opt = GLOBAL_PROCESS_REGISTRY.lock().unwrap();
                *registry_opt = Some(arc_system.registry());
                
                *system_opt = Some(arc_system.clone());
                arc_system
            },
            Err(e) => {
                panic!("Failed to create global ActorSystem: {:?}", e);
            }
        }
    } else {
        system_opt.as_ref().unwrap().clone()
    }
}

/// 获取全局 ProcessRegistry
pub fn get_registry() -> Arc<ProcessRegistry> {
    let registry_opt = GLOBAL_PROCESS_REGISTRY.lock().unwrap();
    
    if let Some(registry) = registry_opt.as_ref() {
        registry.clone()
    } else {
        // 如果没有初始化，先初始化 ActorSystem
        drop(registry_opt); // 释放锁
        get_or_create_system();
        
        // 然后再获取 ProcessRegistry
        GLOBAL_PROCESS_REGISTRY.lock().unwrap().as_ref().unwrap().clone()
    }
}

/// A wrapper for ActorMessageInvoker that includes a mutex
struct MutexInvoker {
    /// The inner invoker
    inner: Mutex<ActorMessageInvoker>,
}

impl MutexInvoker {
    /// Create a new mutex invoker
    fn new() -> Self {
        Self {
            inner: Mutex::new(ActorMessageInvoker::new()),
        }
    }
    
    /// Set the actor
    fn set_actor(&self, actor: Box<dyn Actor<Context = DefaultActorContext>>) -> Result<(), String> {
        match self.inner.lock() {
            Ok(mut inner) => {
                inner.set_actor(actor);
                Ok(())
            },
            Err(_) => Err("Failed to lock mutex".to_string()),
        }
    }
}

impl MessageInvoker for MutexInvoker {
    fn invoke_user_message(&self, message: Box<dyn Any + Send + Sync>) {
        if let Ok(inner) = self.inner.lock() {
            inner.invoke_user_message(message);
        }
    }
    
    fn invoke_system_message(&self, message: SystemMessage, pid: &PID) {
        if let Ok(inner) = self.inner.lock() {
            inner.invoke_system_message(message, pid);
        }
    }

    fn is_alive(&self) -> bool {
        if let Ok(inner) = self.inner.lock() {
            inner.is_alive()
        } else {
            false
        }
    }
    
    fn escalate_failure(&self, reason: Box<dyn Any + Send + Sync>, message: Option<Box<dyn Any + Send + Sync>>) {
        if let Ok(inner) = self.inner.lock() {
            inner.escalate_failure(reason, message);
        } else {
            error!("Actor failure escalated: {:?}", reason);
        }
    }
}

impl Debug for MutexInvoker {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MutexInvoker")
            .field("inner", &"<locked>")
            .finish()
    }
}

trait AnyClone {
    fn clone_any(&self) -> Box<dyn Any + Send + Sync>;
}

impl AnyClone for Box<dyn Any + Send + Sync> {
    fn clone_any(&self) -> Box<dyn Any + Send + Sync> {
        // 尝试常见类型
        if let Some(s) = self.downcast_ref::<String>() {
            return Box::new(s.clone());
        }
        if let Some(i) = self.downcast_ref::<i32>() {
            return Box::new(*i);
        }
        if let Some(b) = self.downcast_ref::<bool>() {
            return Box::new(*b);
        }
        if let Some(u) = self.downcast_ref::<u32>() {
            return Box::new(*u);
        }
        if let Some(u) = self.downcast_ref::<u64>() {
            return Box::new(*u);
        }
        if let Some(f) = self.downcast_ref::<f32>() {
            return Box::new(*f);
        }
        if let Some(f) = self.downcast_ref::<f64>() {
            return Box::new(*f);
        }
        
        // 如果一切都失败，返回一个空的Box
        Box::new(())
    }
}

/// Clone box for Any + Send + Sync
trait AnyBoxClone {
    fn clone_box(&self) -> Box<dyn Any + Send + Sync>;
}

impl<T: Any + Send + Sync + Clone + 'static> AnyBoxClone for Box<T> {
    fn clone_box(&self) -> Box<dyn Any + Send + Sync> {
        Box::new((**self).clone())
    }
}

impl AnyBoxClone for Box<dyn Any + Send + Sync> {
    fn clone_box(&self) -> Box<dyn Any + Send + Sync> {
        // Default to empty box if we can't clone
        if let Some(cloneable) = self.downcast_ref::<Box<dyn AnyBoxClone>>() {
            return cloneable.clone_box();
        }
        Box::new(())
    }
}

/// Actor message invoker
struct ActorMessageInvoker {
    /// The actor
    actor: Option<Box<dyn Actor<Context = DefaultActorContext>>>,
}

impl std::fmt::Debug for ActorMessageInvoker {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ActorMessageInvoker")
            .field("actor", &if self.actor.is_some() { "Some(Actor)" } else { "None" })
            .finish()
    }
}

impl ActorMessageInvoker {
    /// Create a new actor message invoker
    pub fn new() -> Self {
        Self {
            actor: None,
        }
    }
    
    /// Set the actor
    pub fn set_actor(&mut self, actor: Box<dyn Actor<Context = DefaultActorContext>>) {
        self.actor = Some(actor);
    }
    
    /// Check if the actor is alive
    pub fn is_alive(&self) -> bool {
        self.actor.is_some()
    }
}

impl MessageInvoker for ActorMessageInvoker {
    fn invoke_user_message(&self, message: Box<dyn Any + Send + Sync>) {
        if let Some(actor) = &self.actor {
            let message_copy = message.clone_any();
            let mut ctx = DefaultActorContext::new(
                PID::new("local", "temp"),
                None,
                message_copy,
            );
            let _ = tokio::runtime::Handle::current().block_on(actor.receive(&mut ctx, message));
        }
    }
    
    fn invoke_system_message(&self, message: SystemMessage, pid: &PID) {
        if let Some(actor) = &self.actor {
            let mut ctx = DefaultActorContext::new(
                pid.clone(),
                None,
                Box::new(()),
            );
            
            match message {
                SystemMessage::Stop => {
                    let _ = tokio::runtime::Handle::current().block_on(actor.stopping(&mut ctx));
                }
                SystemMessage::Restart => {
                    let _ = tokio::runtime::Handle::current().block_on(actor.restarting(&mut ctx));
                }
                _ => {}
            }
        }
    }

    fn is_alive(&self) -> bool {
        self.actor.is_some()
    }
    
    fn escalate_failure(&self, reason: Box<dyn Any + Send + Sync>, _message: Option<Box<dyn Any + Send + Sync>>) {
        error!("Actor failure escalated: {:?}", reason);
    }
}

trait BoxClone {
    fn clone_box(&self) -> Box<dyn Any + Send + Sync>;
}

impl<T: 'static + Send + Sync + Clone> BoxClone for T {
    fn clone_box(&self) -> Box<dyn Any + Send + Sync> {
        Box::new(self.clone())
    }
}

// Extension trait for Box<dyn Any + Send + Sync>
trait AnyBox {
    fn clone_box(&self) -> Box<dyn Any + Send + Sync>;
}

impl AnyBox for Box<dyn Any + Send + Sync> {
    fn clone_box(&self) -> Box<dyn Any + Send + Sync> {
        if let Some(val) = self.downcast_ref::<Box<dyn BoxClone>>() {
            return val.clone_box();
        }
        
        // 尝试常见类型
        if let Some(s) = self.downcast_ref::<String>() {
            return Box::new(s.clone());
        }
        if let Some(i) = self.downcast_ref::<i32>() {
            return Box::new(*i);
        }
        if let Some(b) = self.downcast_ref::<bool>() {
            return Box::new(*b);
        }
        
        // 如果一切都失败，返回一个空的Box
        Box::new(())
    }
}

// 在 try_respond_to_request 中使用下面的辅助函数
fn clone_response<T: Any + Send + Sync + Clone + 'static>(response: &T) -> Box<dyn Any + Send + Sync> {
    Box::new(response.clone())
}

/// Error type for request operations
#[derive(Debug)]
pub enum RequestError {
    /// The request timed out
    Timeout,
    /// The response type did not match the expected type
    InvalidResponse,
    /// Failed to deliver the message
    MessageDeliveryFailed(String),
}

/// Generate a unique trace ID
fn generate_trace_id() -> String {
    Uuid::new_v4().to_string()
} 